package cn.kgc.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName TokenFilter
 * @Description TODO
 * @Author yaozhaobao
 * @Date 2020/12/20 13:59
 * @Version 1.0
 **/
@Component
public class TokenFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     * 是否执行TokenFilter
     * true 执行过滤器
     * false 不执行过滤器
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        //获取请求路径
        String url = request.getRequestURL().toString();
        System.out.println("用户请求地址："+url);

        //路径中包含"/view/",则执行该过滤器
        return url.contains("/user/");
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("ZullFilter----服务网关过滤器开始处理----------");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String accessToken = request.getHeader("token");
        if (StringUtils.isEmpty(accessToken)) {
            ctx.setSendZuulResponse(false);//过滤该请求，不对其进行路由
            ctx.setResponseStatusCode(401);//响应状态码
            ctx.getResponse().setContentType("text/html;charset=utf-8");//响应内容编码
            ctx.setResponseBody("401! 访问拒绝，请先登录");//响应内容
        }
        return null;
    }
}